package Service;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */



import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author mario rossi
 */
public class Main extends Thread {
    private static Main istanza;
    final int REFRESH_INT = 12*60*60*1000;
    private static volatile Thread running; 
    private String log = "";
    private GestioneDB manager;
    private LettoreCsv a;
    private static boolean flag;
    private Main(){
        manager = GestioneDB.getInstance();
        a=new LettoreCsv();
        manager.inizializzaDB();     
        a.LeggiCsv();
   }
   public static Main getSingleton(){
      if (istanza==null)
         istanza = new Main();
      return istanza; 
   } 
   public void stopThread() {
        flag = false;
        log = log + new Date() + ": Inviato segnale di stop.\n";
        Thread moribondo = running;
        running = null;
        moribondo.interrupt();
        
        
    }
   public static boolean isRunning(){
       return flag;
   }
    
    // Recupera il log del thread.
    public String getLog() {
        return log;
    }
    
    // Svuota il log del thread.
    public void emptyLog() {
        log = "";
    }
    @Override
    public void run() {
          
        try {
        while (flag){   
            log = log + new Date() + ": Inizio aggiornamento database.\n";
            
            
            //manager.stampaCitta();
            manager.aggiornaPrevisioniDB();
            //manager.stampaPrevisioni();
            
            log =log + new Date() + ": Fine aggiornamento database.\n";
            Thread.sleep(REFRESH_INT);
        }
        }
        catch (InterruptedException ex) {
            //Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
            
            log=log + new Date() + ": Thread fermo.\n";
            Thread.currentThread().interrupt();
            //System.err.println(ex);
        }
        catch(Exception ex){
            log=log + new Date() + ": Thread fermo.\n";
        }
    }

    @Override
    public synchronized void start() {
        log=log + new Date() + ": Thread avviato.\n";
        flag=true;
        running = new Thread(this);
        running.start();
        
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        try {
            /* Prova connessioneDB*/
           Main m = getSingleton();
           m.start();
           System.out.println("qui");
           //Thread.sleep(5000);
           m.stopThread();
           Thread.sleep(5000);
           System.out.println(m.getLog());
        } catch (Exception ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        }
       
       
    }

}
